import { ref, computed, onMounted, watch } from 'vue'
import { defineStore } from 'pinia'
import { getLoacl } from '@/api/Amap/local'

export const useCityStore = defineStore('city', () => {
  const loaclCity = ref('')
  const cityList = ref([])
  const nowCity = ref('')

  function setNowCity(city) {
    nowCity.value = city
  }

  function addCityList(city) {
    if (cityList.value.includes(city)) {
      cityList.value.splice(cityList.value.indexOf(city), 1)
    }
    cityList.value.unshift(city)
    if (cityList.value.length > 3) {
      cityList.value.pop()
    }
  }
  onMounted(() => {
    const city = localStorage.getItem('city')
    if (city) {
      nowCity.value = city
    } else {
      nowCity.value = '北京'
    }
    const cityListStr = localStorage.getItem('cityList')
    if (cityListStr) {
      cityList.value = JSON.parse(cityListStr)
    }

    getLoacl().then(res => {
      loaclCity.value = res.city
      //console.log(res)
    })
  })

  watch(nowCity, (newVal) => {
    localStorage.setItem('city', newVal)
  }, { deep: true })
  watch(cityList, (newVal) => {
    localStorage.setItem('cityList', JSON.stringify(newVal))
  }, { deep: true })

  return {
    loaclCity,
    cityList,
    nowCity,
    setNowCity,
    addCityList
  }

})
